package com.bristua.mall.common.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hrt
 * @date 2018年1月5日
 * @description
 * http请求工具类
 */
public class HttpUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
	/**
	 * 超时时间
	 */
	private static final int timeOut = 1000*20;
	/**
	 * 超时编码
	 */
	public static final String CODE_TIMEOUT = "TIMEOUT8888";
	/**	上传图片，目标网址	**/
	public static final String UPLOAD_IMG_URL = "http://localhost:9031/upload.jsp";

	/**
	 * POST请求GBK
     * 发送http报文
     * @param reqData 请求数据
     * @param url 请求地址
     * @return
     * @throws IOException
     */
    public static String excute(String reqData, String url) throws IOException {

		HttpClientParams httpClientParams = new HttpClientParams();
		String encoding = "gbk";
		String contentType = "text/html";
		httpClientParams.setContentCharset(encoding);
		httpClientParams.setHttpElementCharset(encoding);
		HttpClient httpClient = new HttpClient(httpClientParams);
		httpClient.getHostConfiguration().setHost(url);
		HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams();
		httpConnectionManagerParams.setConnectionTimeout(timeOut);
		httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(1);
		httpConnectionManagerParams.setMaxTotalConnections(20);
		httpConnectionManagerParams.setSoTimeout(timeOut);
		httpClient.getHttpConnectionManager().setParams(httpConnectionManagerParams);
		PostMethod postMethod = null;
		try {
			postMethod = new PostMethod(url);
			RequestEntity requestEntity = new StringRequestEntity(reqData, contentType, encoding);
			postMethod.setRequestEntity(requestEntity);
			int httpReturnCode = httpClient.executeMethod(postMethod);
			if(HttpStatus.SC_OK != httpReturnCode){
				logger.error("http请求返回错误状态码：{}", httpReturnCode);
			}
			String responseBody = postMethod.getResponseBodyAsString();
			postMethod.releaseConnection();
			return responseBody;
		} catch(SocketTimeoutException e) {
			logger.error("请求超时");
			return CODE_TIMEOUT;
		}catch (UnsupportedEncodingException e) {
			logger.error("编码异常");
			throw e;
		} catch (HttpException e) {
			logger.error("http异常");
			throw e;
		} catch (IOException e) {
			logger.error("io异常");
			throw e;
		} finally {
			postMethod.releaseConnection();
		}
	}

    /**
     * UTF-8
     * 发送get请求，返回json
     * @param url
     * @return
     * @throws IOException
     */
    public static Map<String, String> getJson(String url) {

    	Map<String, String> result = null;
    	ByteArrayOutputStream bos = null;
    	try{
        	URL reqUrl = new URL(url);
        	HttpsURLConnection httpsConn = (HttpsURLConnection) reqUrl.openConnection();
        	byte[] tmp = new byte[1024];
    		bos = new ByteArrayOutputStream();
    		int len = -1;
    		while((len = httpsConn.getInputStream().read(tmp))!=-1){
    			bos.write(tmp,0,len);
    		}
        	String jsonStr = new String(bos.toByteArray(),"utf-8");
        	ObjectMapper mapper = new ObjectMapper();
        	result = mapper.readValue(jsonStr, new TypeReference<HashMap<String,String>>(){});
    	} catch (Exception e) {
    		logger.error(url + "接口调用失败", e);
    	} finally {
    		try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
    	}
		return result;
    }

    /**
     * UTF-8
     * 发送post请求，返回json
     * @param url
     * @param json
     * @return
     */
    public static String postJson(String url, String json) {
		String ret = null;
		HttpClient client = new HttpClient();
		PostMethod myPost = new PostMethod(url);
		try {
			myPost.setRequestEntity(new StringRequestEntity(json, "application/x-www-form-urlencoded","utf-8"));
			int status = client.executeMethod(myPost);
			if(status == HttpStatus.SC_OK){
				BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int s = 0;
				while((s=bis.read(buffer))!=-1){
					baos.write(buffer,0,s);
				}
				byte[] data = baos.toByteArray();
				ret = new String(data, 0, data.length, "utf-8");
				baos.close();
				bis.close();
			}
		} catch (Exception e) {
			logger.error(url + "接口调用失败", e);
		} finally{
			myPost.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}
		return ret;
	}

	/**
	 * UTF-8
	 * 发送post请求，返回json
	 * @param url
	 * @return
	 */
	public static String get(String url) {
		String ret = null;
		HttpClient client = new HttpClient();
		GetMethod myPost = new GetMethod(url);
		try {
			int status = client.executeMethod(myPost);
			if(status == HttpStatus.SC_OK){
				BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
				byte[] buffer = new byte[1024];
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int s = 0;
				while((s=bis.read(buffer))!=-1){
					baos.write(buffer,0,s);
				}
				byte[] data = baos.toByteArray();
				ret = new String(data, 0, data.length, "gbk");
				baos.close();
				bis.close();
			}
		} catch (Exception e) {
			logger.error(url + "接口调用失败", e);
		} finally{
			myPost.releaseConnection();
			client.getHttpConnectionManager().closeIdleConnections(0);
		}
		return ret;
	}

    /**
     * 上传图片
     * @param file	上传得文件
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static void uploadFileByMutipart(MultipartFile file) throws ClientProtocolException, IOException {
    	uploadFile(file.getInputStream() , file.getName());
    }

    /**
     * 上传图片文件
     * @param is	文件输入流
     * @param name	文件名称
     * @throws ClientProtocolException
     * @throws IOException
     */
    private static void uploadFile(InputStream is , String name) throws ClientProtocolException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        HttpPost httpPost = new HttpPost(UPLOAD_IMG_URL);
        httpPost.setConfig(requestConfig);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        //multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

        //File file = new File("F:\\Ken\\1.PNG");
        //FileBody bin = new FileBody(file);

        //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
        //当设置了setSocketTimeout参数后，以下代码上传PDF不能成功，将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
        //multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
        multipartEntityBuilder.addBinaryBody("file" , is , ContentType.create("image/jpeg") , name);
        //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
       // multipartEntityBuilder.addTextBody("comment", "this is comment");
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);
        httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        int statusCode= httpResponse.getStatusLine().getStatusCode();
        if(statusCode == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String str = "";
            InputStreamReader isr = new InputStreamReader(responseEntity.getContent());
            char[] buf = new char[1024];
            while (isr.read(buf) != -1) {
            	buffer.append(buf);
            }
            /*
            while(StringUtils.isNotEmpty(str = reader.readLine())) {
                buffer.append(str);
            }
                 */
            System.out.println(buffer.toString());
        }

        httpClient.close();
        if(httpResponse!=null){
            httpResponse.close();
        }

    }


	public static String sendPost(String url,String requestData){
		HttpClientParams httpClientParams = new HttpClientParams();
		String encoding = "UTF-8";
		String contentType = "application/json";
		httpClientParams.setContentCharset(encoding);
		httpClientParams.setHttpElementCharset(encoding);
		HttpClient httpClient = new HttpClient(httpClientParams);
		httpClient.getHostConfiguration().setHost(url);
		HttpConnectionManagerParams httpConnectionManagerParams = new HttpConnectionManagerParams();
		httpConnectionManagerParams.setConnectionTimeout(5000);
		httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(1);
		httpConnectionManagerParams.setMaxTotalConnections(20);
		httpConnectionManagerParams.setSoTimeout(5000);
		httpClient.getHttpConnectionManager().setParams(httpConnectionManagerParams);
		PostMethod postMethod = null;
		try {
			postMethod = new PostMethod(url);
			RequestEntity requestEntity = new StringRequestEntity(requestData , contentType, encoding);
			postMethod.setRequestEntity(requestEntity);
			httpClient.executeMethod(postMethod);
			String responseBody = postMethod.getResponseBodyAsString();
			return StringUtils.isEmpty(responseBody) ? null : responseBody;
		}catch (Exception e) {
//			LogUtil.commError(e,"http请求异常");
		} finally {
			postMethod.releaseConnection();
		}
		return null;
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		String url = "http://video001.guduokeji.com/api/user/send_sms";
		Map map = new HashMap();
		map.put("mobile","15080453418");
		String s = JsonUtil.toJson(map);
		String s1 = HttpUtils.postJson(url, "mobile=15080453418");
		System.out.println(s1);
//    	String url ="http://localhost:3000/purchaser/queryPurchaserName.htm?purchaserId=888030537697207";
//		String s = HttpUtils.get(url);
//		Map map = new HashMap();
//		map.put("purchaseId","888030277820608");
//		map.put("startTime","2019-01-02 00:00:00");
//		map.put("endTime","2019-01-02 23:59:59");
//		String s1 = HttpUtils.sendPost("http://localhost:5000/report/directcharge/query", JsonUtils.toJson(map));
//		System.out.println(s1);
    	/*String url = "https://oapi.dingtalk.com/service/get_suite_token";
    	JSONObject json = new JSONObject();
    	json.put("suite_key", "suitellidqnfodoqwtdvf");
    	json.put("suite_secret", "5Uz9qqk6N3GzYo5SGN9OGVS30Oia3a16b4T_ZVtasCZk7zwRwXs_DHVNH-HkePX1");
    	json.put("suite_ticket", "Vh34LN9Wp9CxboZN2Et69bD87FuWhOuVoOQz3DwL9W1iKd6XOQBqUtNxcT0clgrsOzstc9U8YWvyoD8PoSpKMK");
    	String result = postJson(url, json.toJSONString());
    	System.out.println(result);*/
//    	File file = new File("D:/ydds/server/tomcat-static/webapps/ROOT/uploadImg/img/logo.png");
//    	uploadFile(new FileInputStream(file) , "1.png");
    }
}
